package guitforl.wrappers

import guitforl.invocation.UserProcess
import collection.mutable.HashMap
import java.awt.event.{MouseAdapter, MouseEvent}
import javax.swing.{JOptionPane, JButton}

/**
 * (^_^)
 * User: Chris
 * Date: 08.07.2010
 * Time: 11:32:40
 */

class ButtonWrapper(private val caption: String,
                    private val path: String,
                    private val edits: HashMap[String, EditWrapper],
                    private val requiredEdits: List[String],
                    private val updateFields: List[String],
                    private val update: (String) => Unit) extends JButton {
  setText(caption)

  addMouseListener(new MouseAdapter {
    override def mouseClicked(e: MouseEvent) = {
      val checkingResult = checkEdits
      if (checkingResult._1 && updateFields.nonEmpty) {
        val process = new UserProcess(path)        
        process.callWithParam(requiredEdits.map(edit => "-" + edit + "='" + edits(edit).getText + "'"))        
        updateFields.foreach {name => update(name)}
      } else if (!checkingResult._1){
        JOptionPane.showMessageDialog(getParent, "Some field are empty :\n" + checkingResult._2);
      }
    }
  })

  def checkEdits(): Tuple2[Boolean, String] = {
    val emptyEdits: String = requiredEdits.foldLeft("")((a, b) => if (edits(b).isEmpty) a + b + "\n" else a)
    (emptyEdits.equals(""), emptyEdits)
  }

}